package com.example.app.components


import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.width
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay

@Composable
fun RememberUpdatedStateExample(
    modifier: Modifier = Modifier,
    scaffoldState: ScaffoldState = rememberScaffoldState()
) {
    var showMethod by remember { mutableStateOf(0) }

    val color = { select: Boolean ->
        if (select) Color.Magenta else Color.Gray
    }

    val texts = listOf("哦", "我知道了")

    val timeoutList = List<suspend () -> Unit>(texts.size) {
        return@List {
            scaffoldState.snackbarHostState.showSnackbar(
                message = "你超时了~(￣▽￣)~*",
                actionLabel = texts[it]
            )
        }
    }

    Scaffold(modifier = modifier, scaffoldState = scaffoldState) { innerPadding ->
        Column() {
        repeat(texts.size) {
            MaterialTheme(colors = MaterialTheme.colors.copy(primary = color(showMethod == it))) {
                Button(
                    onClick = { showMethod = it },
                    modifier = Modifier.width(120.dp)
                ) {
                    Text(texts[it])
                }
            }
        }
        LoadingScreen(timeoutList[showMethod])
    }
    }
}

@Composable
fun LoadingScreen(onTimeout: suspend () -> Unit, n: Int = 10) {
    val currentOnTimeout by rememberUpdatedState(onTimeout)
    var num by remember {
        mutableStateOf(0)
    }
    Text(text = "$num")
    Log.i("=====", "函数重组")
    Button(onClick = {
        num++
    }) {
       Text(text = "BUtton")
    }
    LaunchedEffect(true) {
        var i = 0
        Log.i("====", "函数调用")
        while (i < n) {
            delay(1000)
            Log.e("===", "delay ${i++}")
        }
        currentOnTimeout()
    }
    //假设界面一直在加载
}

@Preview
@Composable
fun RememberUpdateStateSamplePreview() {
    RememberUpdatedStateExample()
}

